//
//  HYSeg.m
//  HaiYue
//
//  Created by skyline on 2017/12/18.
//  Copyright © 2017年 skyline. All rights reserved.
//

#import "HYSeg.h"
@interface HYSeg()
@property (nonatomic, strong) UIView *animationLine;
@property (nonatomic, assign) CGFloat itemWidth;
@end
@implementation HYSeg
- (instancetype)initWithItems:(NSArray *)items
{
    self = [super init];
    if (self)
    {
        self.items = items;
        self.style = HYSegStyleLine;
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (UIView *)animationLine
{
    if (!_animationLine)
    {
        _animationLine = [[UIView alloc] init];
        _animationLine.tag = 1000;
        [self addSubview:_animationLine];
        [_animationLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self);
            make.height.mas_offset(1.0);
        }];
    }
    return _animationLine;
}

- (CGFloat)itemWidth
{
    return CGRectGetWidth(self.bounds) * 1.0 / _items.count;
}

- (void)setItems:(NSArray *)items
{
    if (_items != items)
    {
        _items = items;
        [self addItems];
        [self setupItems];
    }
}

- (void)setStyle:(HYSegStyle)style
{
    if (_style != style)
    {
        _style = style;
        [self setupItems];
    }
}

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    [super setBackgroundColor:backgroundColor];
    [self setupItems];
}

- (void)setBounds:(CGRect)bounds
{
    [super setBounds:bounds];
    [self setupItems];
}


- (void)setCurrentIndex:(int)currentIndex
{
    if (_currentIndex != currentIndex)
    {
        self.previousIndex = _currentIndex;
        _currentIndex = currentIndex;
        
        [self animationTransformForBottomLine:_currentIndex - self.previousIndex];
        
        UIButton *button = [self viewWithTag:200 + _currentIndex];
        [self performSelector:@selector(actionHYSeg:) withObject:button];
    }
}

- (void)addItems
{
    [self clearSubView];
    for (int i = 0; i < _items.count; i++)
    {
        NSString * string = _items[i];
        UIButton * button = [[UIButton alloc] init];
        [button setTitle:string forState:UIControlStateNormal];
        [button.titleLabel setFont:[UIFont systemFontOfSize:DefaultFont]];
        button.tag = 200 + i;
        button.selected = (i == 0)?YES:NO;
        _currentIndex = (button.selected)?i:_currentIndex;
        [button addTarget:self action:@selector(actionHYSeg:) forControlEvents:UIControlEventTouchUpInside];
        [button addTarget:self action:@selector(HYSegTouchBegin:) forControlEvents:UIControlEventTouchDown];
        [self addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self);
            make.bottom.equalTo(self);
            if (i == 0)//最左边的位置
            {
                make.left.equalTo(self);
            }
            else if (i == self.items.count - 1 && self.items.count > 2 )//最右边的位置 并且items的个数大于2
            {
                make.right.equalTo(self);
            }
            else//中间的
            {
                UIButton * previousBtn = [self viewWithTag:i - 1 + 200];
                make.left.equalTo(previousBtn.mas_right);
                if (self.items.count % 2 == 0 && i == self.items.count / 2 - 1)//如果item.count是双数，并且当前的item是位于最中间的两个item偏左边的
                {
                    make.right.equalTo(self.mas_centerX);
                }
                else if (self.items.count % 2 == 0 && i == self.items.count / 2)//如果item.count是双数，并且当前的item是位于最中间的两个item偏右边的
                {
                    make.left.equalTo(self.mas_centerX);
                }
                else if (self.items.count % 2 && i == (self.items.count - 1) / 2)//如果item.count是单数，并且当前的item是位于最中间的的item
                {
                    make.centerX.equalTo(self.mas_centerX);
                }
            }
        }];
    }
}

- (void)setupItems
{
    self.layer.cornerRadius = (self.style == HYSegStyleCircle)?self.bounds.size.height / 2.0:0;
    self.layer.masksToBounds = YES;
    
    for (UIButton * button in [self subviews])
    {
        if (button.tag >= 200 && button.tag < 500)
        {
            [button setTitleColor:self.titleColor forState:UIControlStateNormal];
            [button setTitleColor:self.selectedtTitleColor forState:UIControlStateSelected];
            [button setTitleColor:self.selectedtTitleColor forState:UIControlStateHighlighted];
            button.backgroundColor = (button.selected && self.style == HYSegStyleCircle)?self.titleColor:self.backgroundColor;
            button.layer.cornerRadius = (self.style == HYSegStyleCircle)?self.bounds.size.height / 2.0:0.0;
            button.layer.masksToBounds = YES;
            [button  mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_offset(self.itemWidth);
            }];
        }
    }
    
    //
    if (self.style == HYSegStyleLine)
    {
        self.animationLine.backgroundColor = self.selectedtTitleColor;
        [self.animationLine mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_offset(self.itemWidth);
            make.left.equalTo(self).with.offset(_currentIndex * self.itemWidth);
        }];
    }
}

- (void)clearSubView
{
    for (UIView *view in [self subviews])
    {
        if (view.tag != 1000)
        {
            [view removeFromSuperview];
        }
    }
}

- (void)animationTransformForBottomLine:(CGFloat)x
{
    if (self.style == HYSegStyleLine)
    {
        [UIView animateWithDuration:0.5 animations:^{
            self.animationLine.transform =  CGAffineTransformTranslate(self.animationLine.transform,x * self.itemWidth, 0);
        }];
    }
}

- (void)actionHYSeg:(UIButton *)sender
{
    if (!sender.selected)
    {
        _currentIndex = (int)sender.tag - 200;
        sender.selected = YES;
        
        [UIView animateWithDuration:0.5 animations:^{
            sender.backgroundColor = self.selectedItemColor;
        }];
        
        for (UIButton *button in [self subviews])
        {
            if (button.tag >= 200 && button.tag < 500 && button.tag != sender.tag)
            {
                button.selected = !sender.selected;
                button.backgroundColor = [UIColor clearColor];
            }
        }
        [self sendActionsForControlEvents:UIControlEventValueChanged];
    }
}

- (void)HYSegTouchBegin:(UIButton *)sender
{
    if (self.style == HYSegStyleLine)
    {
        sender.backgroundColor = RGBA(120,230,220,0.5);
    }
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
